library(ggplot2)
library(readstata13)
library(cregg)
library(tidyverse)

rm(list = ls())

getwd()

#Main Paper####
##Data Import and Formatting####
data1<-read.dta13("Code/Study1/merged_conjoint_study1.dta")
#Two respondents did not have a record of seeing conjoint attributes
data1<-data1 %>% filter(resp_id !="341")
data1<-data1 %>% filter(resp_id !="695")

#Code Party ID 
data1<-data1 %>%
  mutate(pid3_lean = case_when(
                             Q3 == 1 | Q6 == 2 ~ 'Democrat',
                             Q3 == 2 | Q6 == 1 ~ 'Republican',
                             Q6 == 3 ~ 'Independent'))
data1$pid3_lean<-as.factor(data1$pid3_lean)

##Initial Coding 
data2<-data1 %>% select(c("Y_choice","resp_id","choiceNum","locNum","id","registration","speech","votemethod","wait","watcher", "diff", "pid3_lean", "Q31"))

data3<-data2 %>%
  mutate(Voter_ID=recode_factor(id,
                                "None Required" = "None Required",
                                "Signature on Sign in" = "Signature",
                                "Photo ID" = "ID",
                                " Photo ID + Signature on Sign in" = "Sig. and ID"),
         Registration=recode_factor(registration, 
                                    "Registration must be complete 30 days before the election"="30 days prior",
                                    "Registration must be complete 8 days before the election"="8 days prior",
                                    "Same day registration not permitted" = "No same day",
                                    "Same day registration permitted with proper ID" = "Same day with ID",
                                    "Same day registration permitted"="Same day allowed"),
         Speech=recode_factor(speech,
                              "No campaigning allowed within 100 feet"="< 100 ft",
                              "No campaigning allowed within 50 feet"="< 50 ft",
                              "No campaigning allowed within the building"="No campaigning",
                              "No restriction on campaigning"="No restriction"),
         Vote_Method=recode_factor(votemethod,
                                   "Machine (touchscreen), no paper receipt"="Machine/no receipt",
                                   "Machine (touchscreen), prints paper receipt"="Machine/receipt",
                                   "Machine (touchscreen), paper receipt w/ automatic manual audit"="Machine/receipt/automatic audit",
                                   "Machine (touchscreen), machine count w/ manual audit for very close races"="Machine/automatic audit",
                                   "Paper ballot, hand counted"="Paper/hand count",
                                   "Paper ballot, machine counted"="Paper/machine count"),
         Wait_Time=recode_factor(wait,
                                 "<10 minutes"="<10 min.",
                                 "10-30 minutes"="10-30 min.",
                                 "30 minutes-1 hour"="30-60 min.",
                                 "1-3 hours"="1-3 hr.",
                                 "3+hours"="3+ hr."),
         Poll_Watchers=recode_factor(watcher,
                                     "Not allowed"="Not allowed",
                                     "Only watchers selected by the political parties"="Partisan",
                                     "Only watchers selected by the political parties, with an identification badge"="Partisan/ID",
                                     "Only watchers employed by the state"="State",
                                     "Only watchers employed by the state, with an identification badge"="State/ID",
                                     "Both state and political party watchers"="State/Partisan",
                                     "Both state and political party watchers, all with an identification badge"="State/Partisan/ID"))
with(data3, table(Poll_Watchers))
with(data3, table(Wait_Time))
with(data3, table(Vote_Method))
with(data3, table(Speech))
with(data3, table(Registration))
with(data3, table(Voter_ID))
with(data3, table(pid3_lean))

save.dta13(data3, "analysis_dataset_study1.dta")

##Analysis 1 - AMCE#### 
output<-cj(data3, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
           , id = ~ resp_id)

x<-plot(output, legend_post="off")
x+geom_hline(yintercept=c(6,13,18,24,29), color="grey")+
  geom_point(size=3)+
  theme_bw()+
  theme(legend.title=element_blank(), legend.position="off")+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))

#Figure 2 in main paper 
ggsave(
  "Figures/Main Paper/study1_AMCE_binary.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

##Analysis 2 - Marginal Means by Party ID#### 

summary(data3$pid3_lean)
data3_pid<-data3 %>%filter(pid3_lean !="NA",  pid3_lean !="Independent")
table(data3_pid$pid3_lean)

data3_pid<-data3_pid %>% mutate(RepDem=recode(pid3_lean, 
                                              "Democrat"="Dem.",
                                              "Republican"="Rep."))
with(data3_pid,RepDem)
data3_pid$RepDem<-droplevels(data3_pid$RepDem)

output<-cj(data3_pid,Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time,
           id = ~ resp_id,
           by=~RepDem,
           estimate="mm")
output
with(output, table(RepDem))

plot(output, group="RepDem", size=3)+aes(shape=RepDem,color=RepDem)+
  geom_hline(yintercept=c(6,13,18,24,29), color="grey")+
  scale_shape_manual(values=c(15, 16),na.translate=F) + 
  scale_color_manual(values=c("dark blue","red"), na.translate=F)+
  theme_bw()+
  theme(legend.position = "top", legend.title=element_blank())+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))

#Figure 3 in main paper 
ggsave(
  "Figures/Main Paper/study1_marginalmean_binary.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

#Appendix####

##Continuous Outcome#### 

###AMCE#### 
output<-cj(data3, diff~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
           , id = ~ resp_id)
x<-plot(output, legend_post="off")
x+geom_hline(yintercept=c(6,13,18,24,29), color="grey")+
  geom_point(size=3)+
  theme_bw()+
  theme(legend.title=element_blank(), legend.position="off")+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))

#Figure B1 
ggsave(
  "Figures/Appendix/study1_AMCE_diff.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

###Marginal Means by Party####

summary(data3$pid3_lean)
data3_pid<-data3 %>%filter(pid3_lean !="NA",  pid3_lean !="Independent")
table(data3_pid$pid3_lean)

data3_pid<-data3_pid %>% mutate(RepDem=recode(pid3_lean, 
                                              "Democrat"="Dem.",
                                              "Republican"="Rep."))
with(data3_pid,RepDem)
data3_pid$RepDem<-droplevels(data3_pid$RepDem)

output<-cj(data3_pid,diff~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time,
           id = ~ resp_id,
           by=~RepDem,
           estimate="mm")
output
with(output, table(RepDem))

plot(output, group="RepDem", size=3)+aes(shape=RepDem,color=RepDem)+
  geom_hline(yintercept=c(6,13,18,24,29), color="grey")+
  scale_shape_manual(values=c(15, 16),na.translate=F) + 
  scale_color_manual(values=c("dark blue","red"), na.translate=F)+
  theme_bw()+
  theme(legend.position = "top", legend.title=element_blank())+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))

#Figure B2 
ggsave(
  "Figures/Appendix/study1_marginalmean_diff.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

##AMCE by Rounds####

results_data<-data3 %>% mutate(task_num=as.factor(choiceNum),
                               profile_order=as.factor(locNum))

output_by_round<-cj(results_data, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
           , id = ~ resp_id, by=~task_num, estimate="amce")
summary(output_by_round)

marginal_means_plot_by_task <- ggplot(output_by_round, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~task_num, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task
#Figure C1
ggsave("Figures/Appendix/Study 1 - AMCE by Rounds.png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

output_by_round_watchers<-output_by_round %>% filter(feature=="Poll_Watchers")
marginal_means_plot_by_task2 <- ggplot(output_by_round_watchers, aes(y=estimate, x=fct_rev(level), color=task_num,  group=fct_rev(task_num))) +
  #facet_grid(~task_num, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.5)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.5)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task2
#Figure C2
ggsave("Figures/Appendix/Study 1 - AMCE by Rounds (Watchers Only).png",marginal_means_plot_by_task2, dpi=300, width=8, height=6)


## AMCE by Profile Order####

output_by_profile<-cj(results_data, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                    , id = ~ resp_id, by=~profile_order, estimate="amce")
summary(output_by_profile)

marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~profile_order, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task

#Figure C3 
ggsave("Figures/Appendix/Study 1 - AMCE by Profile Order.png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

output_by_profile_watchers<-output_by_profile %>% filter(feature=="Poll_Watchers")
marginal_means_plot_by_task2 <- ggplot(output_by_profile_watchers, aes(y=estimate, x=fct_rev(level), color=profile_order,  group=fct_rev(profile_order))) +
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.5)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.5)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task2

#Figure C4
ggsave("Figures/Appendix/Study 1 - AMCE by Profile Order (Watchers Only).png",marginal_means_plot_by_task2, dpi=300, width=8, height=4)

##Subsets by State and Watcher Rules####
#Conjoint Data 

data3_tomerge<-data3 %>% rename("State_Code"="Q31") 
summary(data3_tomerge)

#State rule data 
data_state<-read.csv("state watcher rules.csv")
summary(data_state)
with(data_state, table(can_challenge))
with(data_state, table(can_speak))
with(data_state, table(prohibit_election))
with(data_state, table(called_watchers))
with(data_state, table(official_id))

data_merged<-left_join(data3_tomerge, data_state, by="State_Code") %>% filter(State !="West Virginia")
summary(data_merged)

#AMCE by Rules 
data_merged2<-data_merged
data_merged2$"can_challenge"<-as.factor(data_merged2$"can_challenge")
data_merged2$"can_speak"<-as.factor(data_merged2$"can_speak")
data_merged2$"prohibit_election"<-as.factor(data_merged2$"prohibit_election")
data_merged2$"called_watchers"<-as.factor(data_merged2$"called_watchers")
data_merged2$"official_id"<-as.factor(data_merged2$"official_id")

summary(data_merged2)

#Can Challenge 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~can_challenge, estimate="amce")
output_by_profile<-output_by_profile %>% mutate(can_challenge=recode(can_challenge, 
                                                                      "0"="Not allowed to challenge",
                                                                      "1"="Allowed to challenge"))

marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~can_challenge, scales="free")+
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  ggtitle("Study 1")+
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task

#Figure D1 
ggsave("Figures/Appendix/State Rules/Study 1 - AMCE by State Rules (Challenge Voters).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Can Speak 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~can_speak, estimate="amce")
output_by_profile<-output_by_profile %>% mutate(can_speak=recode(can_speak, 
                                                                     "0"="Speaking to voters prohibited",
                                                                     "1"="Speaking to voters allowed"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~can_speak, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 1")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")

#Figure D5 
ggsave("Figures/Appendix/State Rules/Study 1 - AMCE by State Rules (Speak to Voters).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Prohibit Election Engagement 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~prohibit_election, estimate="amce")
summary(output_by_profile)
output_by_profile<-output_by_profile %>% mutate(prohibit_election=recode(prohibit_election, 
                                                                 "0"="Electioneering Allowed",
                                                                 "1"="Electioneering Prohibited"))

marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~prohibit_election, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 1")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D2 
ggsave("Figures/Appendix/State Rules/Study 1 - AMCE by State Rules (Prohibit Electioneering).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Called Watchers  
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~called_watchers, estimate="amce")
summary(output_by_profile)

output_by_profile<-output_by_profile %>% mutate(called_watchers=recode(called_watchers, 
                                                                         "0"="Not Called Poll Watcher",
                                                                         "1"="Called Poll Watcher"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~called_watchers, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 1")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D4 
ggsave("Figures/Appendix/State Rules/Study 1 - AMCE by State Rules (Watcher Label).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Required Display ID 

data_merged3<-  data_merged2 %>% filter(official_id==1 | official_id==0)
data_merged3$id_required<-droplevels(data_merged3$official_id)

output_by_profile<-cj(data_merged3, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~official_id, estimate="amce")
summary(output_by_profile)

output_by_profile<-output_by_profile %>% mutate(official_id=recode(official_id, 
                                                                          "0"="Not required to wear ID",
                                                                          "1"="Required to wear ID"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~official_id, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 1")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D3 
ggsave("Figures/Appendix/State Rules/Study 1 - AMCE by State Rules (Required ID).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)


